<template>
  <el-dialog
    title="新增电子材料"
    :visible.sync="visible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <!-- 分类选择 -->
      <el-form-item label="人员编号">
        <person-rpc ref="personRpc" style="width: 640px" @personRpcCallBack="personRpcCallBack" />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.aac003" placeholder="请输入姓名" :disabled="true" />
      </el-form-item>
      <el-form-item label="业务类型" prop="aaa121">
        <el-select v-model="form.aaa121" placeholder="请选择" filterable allow-create style="width: 640px">
          <el-option
            v-for="item in dict.aaa121"
            :key="item.id"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- 材料基本信息 -->
      <el-form-item label="材料名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入材料名称" />
      </el-form-item>
      <!-- 文件上传 -->
      <el-form-item label="上传材料" prop="files">
        <el-upload
          ref="upload"
          class="upload-demo"
          :action="uploadUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          :headers="uploadHeaders"
          :file-list="form.files"
          :auto-upload="false"
          :data="uploadData"
          multiple
          :limit="10"
          :on-exceed="handleExceed"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <!--          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
          <div slot="tip" class="el-upload__tip">只能上传jpg/png/pdf/word文件，且不超过10MB</div>
        </el-upload>

        <!-- 文件预览区域 -->
        <div v-if="form.files.length > 0" class="preview-container">
          <div class="preview-title">文件列表：</div>
          <div class="file-list">
            <div v-for="(file, index) in form.files" :key="index" class="file-item">
              <div class="file-info">
                <i :class="getFileIcon(file.name)" />
                <span class="file-name" @click="handlePreview(file)">{{ file.name }}</span>
                <span class="file-size">({{ formatFileSize(file.size) }})</span>
              </div>
              <div class="file-actions">
                <el-button size="mini" @click="handlePreview(file)">预览</el-button>
                <!--                <el-button size="mini" type="danger" @click="handleRemove(file)">删除</el-button>-->
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="fnGb">取 消</el-button>
      <el-button
        type="primary"
        :loading="submitting"
        @click="submitForm"
      >确 定</el-button>
    </span>
    <!-- 文件预览对话框 -->
    <el-dialog
      :title="previewTitle"
      :visible.sync="previewVisible"
      width="80%"
      append-to-body
      top="5vh"
    >
      <div class="preview-content">
        <!-- 图片预览 -->
        <img
          v-if="previewType === 'image'"
          :src="previewUrl"
          style="max-width: 100%; max-height: 70vh; display: block; margin: 0 auto;"
        >

        <!-- PDF预览 -->
        <pdf-preview
          v-else-if="previewType === 'pdf'"
          :file-url="previewUrl"
          style="height: 70vh;"
        />

        <!-- Office文档预览 -->
        <!--        <iframe-->
        <!--          v-else-if="['doc', 'docx', 'xls', 'xlsx'].includes(previewType)"-->
        <!--          :src="`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(previewUrl)}}&embedded=true`"-->
        <!--          width="100%"-->
        <!--          height="70vh"-->
        <!--          frameborder="0"-->
        <!--        />-->

        <!-- 不支持预览的格式 -->
        <!--        <div v-else style="width: 100%; height:70vh">-->
        <!--          <i class="el-icon-document" style="font-size: 50px; color: #909399; " />-->
        <!--          <p style="align: center">该文件格式不支持在线预览</p>-->
        <!--          &lt;!&ndash;          <el-button type="primary" @click="downloadFile(previewUrl, previewTitle)">&ndash;&gt;-->
        <!--          &lt;!&ndash;            <i class="el-icon-download"></i> 下载文件&ndash;&gt;-->
        <!--          &lt;!&ndash;          </el-button>&ndash;&gt;-->
        <!--        </div>-->
        <div v-else class="unsupported-preview">
          <i class="el-icon-document" style="font-size: 50px; color: #909399;" />
          <p>该文件格式不支持在线预览</p>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { getToken } from '@/utils/auth'
import PersonRpc from '@/views/ynsb_comm/comm/module/personRpc'
import PdfPreview from '@/views/ynsb_comm/fileupload/PdfPreview'
export default {
  name: 'MaterialAddDialog',
  components: { PdfPreview, PersonRpc },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    personList: {
      type: Array,
      default: () => []
    },
    businessTypeList: {
      type: Array,
      default: () => []
    }
  },
  // 数据字典
  dicts: ['aaa121'],
  data() {
    return {
      form: {
        aac001: '',
        aac003: '',
        aaa121: '',
        name: '',
        materialCode: '',
        description: '',
        files: [],
        validDate: []
      },
      rules: {
        aac001: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ],
        aaa121: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入材料名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入材料描述', trigger: 'blur' }
        ],
        files: [
          { validator: this.validateFiles, trigger: 'change' }
        ]
      },
      businessTypes: [
        { value: '1', label: '业务类型一' },
        { value: '2', label: '业务类型二' },
        { value: '3', label: '业务类型三' }
      ],
      uploadData: {},
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/electronic-material/upload',
      uploadHeaders: {
        'Authorization': 'Bearer ' + getToken()
      },
      // 文件预览相关
      previewVisible: false,
      previewUrl: '',
      previewTitle: '',
      previewType: '',
      submitting: false
    }
  },
  computed: {
    filteredOptions() {
      // 在这里定义您的过滤条件
      return this.dict.aaa121.filter(item =>
        item.value === '040101' || item.value === '040102' || item.value === '030101'
      )
    }
  },
  methods: {
    personRpcCallBack(item) {
      this.form.aac001 = item.aac001
      this.form.aac003 = item.aac003
    },
    // 关闭
    fnGb() {
      this.visible = false
      this.form.aac001 = ''
      this.form.aac003 = ''
      this.$refs.form.resetFields()
      this.form.files = []
      this.$refs.personRpc.restAac001('')
      this.$refs.upload.clearFiles()
      this.$emit('gbCallBack')
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.form.files = []
    },

    // 下载文件
    downloadFile(url, fileName) {
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },

    // 获取文件类型
    getFileType(filename) {
      const extension = filename.split('.').pop().toLowerCase()
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(extension)) {
        return 'image'
      } else if (extension === 'pdf') {
        return 'pdf'
      } else if (['doc', 'docx'].includes(extension)) {
        return 'doc'
      } else if (['xls', 'xlsx'].includes(extension)) {
        return 'xls'
      } else {
        return 'other'
      }
    },
    validateFiles(rule, value, callback) {
      if (this.form.files.length === 0) {
        callback(new Error('请至少上传一个文件'))
      } else {
        callback()
      }
    },

    generateMaterialCode() {
      const timestamp = new Date().getTime()
      const randomNum = Math.floor(Math.random() * 1000)
      return `MAT-${timestamp}-${randomNum}`
    },

    handlePersonChange(val) {
      if (val) {
        this.form.materialCode = this.generateMaterialCode()
      } else {
        this.form.materialCode = ''
      }
    },

    async submitForm() {
      try {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.form.files.length === 0) {
              this.$message.warning('请上传至少一个文件')
              return
            }

            // 设置上传额外参数
            this.uploadData = {
              aac001: this.form.aac001,
              name: this.form.name,
              id: this.id,
              aaa121: this.form.aaa121
            }
            // 开始上传文件
            this.$nextTick(() => {
              this.$refs.upload.submit()
            })
          }
        })
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('提交失败: ' + (error.message || '未知错误'))
      } finally {
        this.submitting = false
      }
    },

    handleClose() {
      this.fnGb()
    },

    handleRemove(file, fileList) {
      this.form.files = fileList
      this.$refs.form.validateField('files')
    },

    // 获取文件图标
    getFileIcon(filename) {
      const extension = filename.split('.').pop().toLowerCase()
      const iconMap = {
        jpg: 'el-icon-picture',
        jpeg: 'el-icon-picture',
        png: 'el-icon-picture',
        gif: 'el-icon-picture'
        // bmp: 'el-icon-picture',
        // pdf: 'el-icon-document',
        // doc: 'el-icon-document',
        // docx: 'el-icon-document',
        // xls: 'el-icon-document',
        // xlsx: 'el-icon-document'
      }
      return iconMap[extension] || 'el-icon-document'
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    // 处理文件变化
    handleFileChange(file, fileList) {
      this.form.name = fileList[0].name.split('.')[0]
      console.log(fileList, '9999999999999999999999')
      // this.beforeUpload(file)
      this.form.files = fileList // 手动更新文件列表
    },
    handlePreview(file) {
      // 设置预览信息
      this.previewTitle = file.name
      this.previewUrl = file.url || URL.createObjectURL(file.raw)
      this.previewType = this.getFileType(file.name)
      this.previewVisible = true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传5个文件，当前已选择 ${fileList.length} 个文件`)
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      const allowedTypes = [
        'image/jpeg',
        'image/png',
        'application/pdf',
        // 'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        // 'application/vnd.ms-excel',
        // 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ]

      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传jpg/png/pdf/word文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      console.log(file, 'beforeUpload')
      return true
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(fileList, 'kkkkk')
      if (response.code === 200) {
        this.$message.success('文件上传成功')
        this.fnGb()
        this.$emit('uploadSuccessBack')
      } else {
        this.$message.error(response.message || '文件上传失败')
      }
      // this.uploading = false
    },

    submitUpload() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>
.upload-demo {
  width: 100%;
}

.el-date-editor.el-range-editor {
  width: 100%;
}

/* 文件列表样式 */
.file-list {
  margin-top: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.file-item:hover {
  background-color: #ebf5ff;
}

.file-item:last-child {
  margin-bottom: 0;
}

.file-icon {
  margin-right: 12px;
  font-size: 24px;
  color: #409EFF;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-status {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.success {
  color: #67C23A;
}

.uploading {
  color: #409EFF;
}

.waiting {
  color: #E6A23C;
}

.file-size {
  margin-left: 10px;
}
.unsupported-preview {
  text-align: center;
  height:70vh;
  padding: 40px 0;
  color: #909399;
}

.unsupported-preview p {
  margin: 15px 0;
}
</style>
